import Vue from 'vue'
import VueRouter from 'vue-router'
import VueCookies from 'vue-cookie'
import { Message } from 'element-ui';
import Index from '@/view/index'
import Login from "@/view/login"

Vue.use(VueRouter)
Vue.use(VueCookies)
Vue.use(Message)

const routes = [
  {
    path: '/index',
    name: 'Index',
    alias: '/',
    component: Index,
    children: [
      {
        path: '/',
        component: () => import('./view/index/components/Main')
      },
      {
        path: 'product/:id',
        component: () => import('./view/detail')
      },
      {
        path: 'detail/:id',
        component: () => import('./view/detail/detail.vue')
      },
      {
        path: 'joincart',
        component: () => import('./view/index/join.vue')
      }
    ]
  },
  {
    path: '/login',
    name: Login,
    component: Login
  },
  {
    path: '/register',
    // name: Register,s
    component: () => import('./view/login/register.vue')
  },
  {
    path: '/cart',
    // name: Cart,
    component: () => import('./view/cart/index.vue'),
    children: [
      {
        path: '/',
        component: () => import('./view/cart/components/Main.vue')
      },
      {
        path: 'order',
        component: () => import('./view/cart/components/Order.vue')
      },
      {
        path: 'orderset/:id',
        component: () => import('./view/cart/components/OrderSet.vue')
      },
      {
        path: 'confirm',
        component: () => import('./view/cart/confirm.vue')
      }
    ]
  }
]
// router.beforeEach((to, from, next) => {
//   var token = this.$cookie.get(userId)
//   if (to.name !== 'login' && !tooken) next({ name: 'login' })
//   else next()
// })

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  var token = VueCookies.get('userId')
  if (to.path !== '/login' && !token){
    next({ path: '/login' })
    Message('您还没有登录，请先登录')
  }
  else {
    document.documentElement.scrollTop = 0;
    next()
  }
})

export default router
